Skip to content

fix(collab,sync): journal-fenced CRDT, multi-hunk diff3, and 8-peer exit safety - #355

Merged
isac322 merged 34 commits into
mainfrom
fix/collab-journal-fenced-diff3
Nov 11, 2026
Merged

isac322 merged 34 commits into
mainfrom
fix/collab-journal-fenced-diff3

Conversation

@isac322

@isac322 isac322 commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR

  • Multiple people editing a meeting note in the browser no longer overwrite each other, trigger false teammate-edit warnings, or spawn .bdrive-conflict-* copies when saving or leaving edit mode, and closing a tab sends pending edits with keepalive when the encoded HTTP request body is at most 60,000 bytes.
  • A second hub instance opening a co-editing room on a stale fold cache can no longer splice older text back over newer edits.
  • Slow or stalled WebSocket connections open a staging buffer after 2.5 seconds and merge back into the live room once the socket connects, instead of locking the tab into solo mode for the rest of the session.
  • Concurrent edits to different sections, adjacent bullet lists, or separate words on the same line now merge automatically across browser uploads, MCP write/edit, live rooms, and bdrive sync.
  • Known gaps: rewrites of the exact same word outside a live room still park a .bdrive-conflict-* copy, a tab-close request body over 60,000 bytes goes out without keepalive and the browser may cancel it, and v0.18.9 hub processes cannot read the new ydoc/head/<path> records, so hubs sharing a storage root must upgrade together.

What & why

Co-editing conflicts and silent rollbacks came from three surfaces disagreeing on who owned the document and how concurrent edits merged:

  1. Multi-instance CRDT seeding and retention (internal/webapp/ycollab.go, collab_relay.go, cmd/bdrive/desktop.go): ydoc/head/<path> now stores {sha, win}, where win is the monotonic winKey of the journal op that produced the stored state. Older folds cannot move the head backwards, and knows() compares states through a scratch merge so histories with deletions match accurately. Empty rooms remain warm for 2 minutes (collabRoomIdleTimeout), Redis streams retain 30 minutes of updates with state republishing on snapshot retries, moveDocLive reconciles outside writes as CRDT item deltas from an atomic snapshot, and POST /api/p/{project}/ycollab/sync (also proxied by bdrive desktop) checkpoints browser edits into the room with an 8-second cross-instance durability wait (snapshotMax lowered from 10s to 6s).
  2. Multi-hunk Myers + Diff3 + intra-line token merge (internal/textmerge/merge.go, frontend/src/lib/merge3.ts, upload.go, mcp.go, internal/syncer/): Both Go and TypeScript now diff with Myers O(ND), merge independent hunks and non-overlapping intra-line word changes, and order same-point insertions deterministically while preserving .json/.jsonl validity. Conditional PUT /api/p/{project}/upload/content and MCP write/edit merge stale If-Match bases on the server and record Op.Base, while internal/syncer merges against the winning op and skips writing a duplicate op when the merged digest already matches the winner.
  3. Browser staging, exit flushing, and 8-peer snapshot tracking (collab.ts, sharedfile.ts, editbeacon.ts, editexit.worker.ts, inline-edit.ts, Editor.tsx, VisualEdit.tsx, FileView.tsx, Browser.tsx, htmledit.go): Replaced the 8-second CollabDoc.stop() cutoff with a 2.5-second onStalled staging buffer (stageDoc in VisualEdit) that checkpoints over ycollab/sync, peeks after ambiguous network failures, and splices minimal hunks on socket sync. save() and offline flushes are single-flight with sequence watermarks. Mod-s checkpoints immediately, and Done awaits saveNow() (now Promise<boolean>) until every edit, including any typed during the save, is saved before leaving, and stays in the editor if the save fails or opens a shrink confirmation. pagehide sends unsent edits with keepalive when the encoded HTTP request body is at most 60,000 bytes (KEEPALIVE_MAX_BYTES, below the browser's 64 KiB in-flight keepalive limit); a larger body goes out as a regular fetch, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. pageshow resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. The VisualEdit iframe stays sandbox="allow-scripts" and never receives a session, token or URL. stampEditable now injects /inline-edit.js synchronously before any page script, so inline-edit.ts captures the native MessageChannel, MessagePort methods and Event.isTrusted first, uncurries the WeakMap/Map/Set builtins it uses, freezes the DOM, Event, Range, Selection and geometry prototypes, opens a private MessageChannel, and sends bd-edit:hello with one port to VisualEdit once; all later editor traffic uses that sealed channel instead of window.postMessage, edits require trusted user events, and pasted marks are whitelisted from the trusted clipboard's text/html only. The bootstrap tag also carries data-src-ranges; inline-edit.ts reads and strips its data-src-* attributes, locks data-bd-src, binds each stamped element once in a private WeakMap (rejecting duplicate or unstamped ranges), and refuses page-script writes to the open element (inEditorCall taint tracking), reporting bd-edit:clobbered instead of saving. The editor itself is mounted inside a closed shadow root (attachShadow({ mode: "closed" }) on a <span data-bd-shadow>), so page scripts cannot reach its live nodes through reflected setters, saved light-DOM references or another realm's DOM setters, and the edited HTML is written back to the element's light DOM on unmount(); detaching the element or the shadow host also raises bd-edit:clobbered. VisualEdit's anchorRanges checks each span's initial HTML against the source slice through an inert <template> (canonicalHTML) before anchoring it or arming the worker. VisualEdit spawns a dedicated same-origin Web Worker (editexit.worker.ts), arms it with the rendered source, the anchored ranges and the live saved text, base sha and document text (kept current through SharedFile's onBaseChange), and hands the iframe one end of a MessageChannel (bd-edit:port). The iframe keeps no edited-span map: inline-edit.ts streams each edit to the worker as bd-edit:span (seq, start, end, html), VisualEdit posts ack with the seq of each patch it applied straight to the worker, and on the iframe's beforeunload/pagehide it posts bd-edit:exit; all span and ack state lives in the worker's isolated realm. After a back/forward-cache restore, VisualEdit re-arms the worker (rearm) with a fresh bd-edit:port, so an edit left unacknowledged on a second close is saved too. The exit-worker save is best-effort and runs only once the worker has started and been armed. The worker splices only anchored, script-free spans onto the render, merges three ways with the current document, refuses an unconfirmed sharp shrink, and saves with the app's own cookie: POST ycollab/sync with park_on_conflict on a hub or desktop, or PUT upload/content on the latest If-Match on a plain folder, so it also works after earlier auto-saves; a same-word clash parks a conflict copy. VisualEdit splices only changed spans inside an element, and post-saved room snapshots advance saved and base without raising #peer-wrote.

Upgrade notes

  • Client wire and local volume on-disk formats remain backward-compatible, and v0.18.10 hubs read the bare-sha ydoc/head/<path> records older hubs wrote.
  • v0.18.10 hubs write ydoc/head/<path> as JSON ({sha, win}), which a v0.18.9 or earlier hub process cannot read. During a mixed-version rollout or a rollback, that older process skips the newest stored room state and falls back to the per-blob CRDT history (ydoc/<sha>) or, when none matches, to fresh file bytes. Multi-instance self-hosted operators should upgrade every hub process sharing a storage root together instead of running v0.18.9 and v0.18.10 side by side.

Architecture changes

architecture/overview.md

The internal/textmerge node now describes the Myers multi-hunk diff3 merge with intra-line token merge and its four exports, and the hub's edge to it covers room reconciliation, conditional upload/content, and MCP write/edit instead of only an outside write under a room.

flowchart LR
    eng["internal/syncer Session.Cycle"]
    srv["internal/webapp Server"]
    tm_old["❌ <s>internal/textmerge: line-level three-way merge, non-overlapping regions only</s>"]
    tm["✅ internal/textmerge: Myers multi-hunk diff3 merge + intra-line token merge<br/>Merge, DiffHunks, RetainsChanges, IsText"]
    eng -->|concurrent edits from two devices| tm
    srv -.->|"❌ <s>an outside write under a co-editing room</s>"| tm_old
    srv -->|"✅ co-editing room reconciliation, conditional upload/content, MCP write / edit on a stale sha"| tm
Loading

architecture/cli-sync.md

textmerge gains DiffHunks, RetainsChanges, and IsText; merge gains latestPut, so conflictCopiesWithState merges the losing op against the winning op, skips the op when the result equals the winner's blob, and records Op.Base on a real merge.

flowchart LR
    Session["Session.conflictCopiesWithState"]
    merge["merge (merge.go)<br/>tryMerge, mergeText, commonAncestor"]
    latestPut["✅ latestPut(path, blob, lists): the op that won"]
    ff["✅ merged blob == winner blob: fast-forward, no op"]
    base["✅ merge op records Op.Base = winning blob"]
    textmerge["textmerge<br/>Merge"]
    tmnew["✅ DiffHunks, RetainsChanges, IsText"]
    Session -->|before a conflict copy| merge
    merge --> latestPut
    merge --> ff
    merge --> base
    merge -->|the line merge itself| textmerge
    textmerge --- tmnew
Loading

architecture/webapp-server.md

Server gains handleYCollabSync, syncDurable/awaitDurable, mergeStaleUpload, moveDocLive, and parkStaleUpload/stepConflictCopy with new edges to ydocs and textmerge, plus a note on park-on-conflict (X-Bdrive-Park-On-Conflict on upload/content, park_on_conflict on ycollab/sync, validMergedText for .json/.jsonl); ydocs gains the ydoc/head roomHeadRec {sha, win} fence, collabRoomIdleTimeout (2m), and snapshotMax (6s, was 10s); CollabConfig gains a 30-minute stream retention; mcpTools now merges a stale sha through the upload door; editView now injects /inline-edit.js synchronously before any page script instead of appending it, with data-src-ranges beside the hash and length.

flowchart LR
    Server["Server"]
    ydocs["ydocs (ygo)"]
    textmerge["textmerge"]
    CollabConfig["CollabConfig<br/>Redis<br/>✅ collabStreamRetention 30m, collabStreamMaxLen 32768"]
    mcpTools["mcpTools write / edit"]
    sync["✅ handleYCollabSync: POST {prefix}ycollab/sync<br/>syncDurable / awaitDurable, ycollabSyncDurableWait 8s<br/>park_on_conflict text checkpoints"]
    msu["✅ mergeStaleUpload + Op.Base on conditional upload/content"]
    park["✅ parkStaleUpload / stepConflictCopy: X-Bdrive-Park-On-Conflict<br/>validMergedText for .json / .jsonl"]
    head["✅ ydoc/head/&lt;path&gt; = roomHeadRec {sha, win}: winKey fence, DeleteSet-safe knows()"]
    live["✅ moveDocLive: CRDT item delta from one atomic snapshot"]
    timers["✅ collabRoomIdleTimeout 2m, snapshotMax 6s"]
    editView["editView (htmledit.go, ?edit=1)<br/>❌ <s>appends /inline-edit.js</s><br/>✅ injects /inline-edit.js synchronously before any page script<br/>✅ data-src-hash, data-src-len, data-src-ranges"]
    Server -->|"serveBlob ?edit=1"| editView
    Server --> park
    Server --> sync
    Server --> msu
    Server -->|"✅ ycollab/sync applies a client state"| ydocs
    Server -->|"✅ mergeStaleUpload (Merge, RetainsChanges)"| textmerge
    ydocs -->|"reconcile an outside write (Merge), ✅ splice as minimal hunks (DiffHunks)"| textmerge
    ydocs --> head
    ydocs --> live
    ydocs --> timers
    CollabConfig -->|AttachRelay| ydocs
    mcpTools -->|"✅ stale sha becomes the If-Match base (staleShaError)"| msu
    msu -->|"✅ unmergeable stale base, park requested"| park
Loading

architecture/webapp-frontend.md

lib gains merge3.ts, frameflush.ts (frameChannel: an in-order queue of iframe messages that drains with bd-edit:flush / bd-edit:flushed before VisualEdit saves; saveLocked: Done's flush carries lock: true, and bd-edit:unlock reopens the frame when saveNow() returns false or throws), editbeacon.ts (ackEditedSpan, unackedExitPatches, applyRenderPatches, buildExitSaveRequest) and editexit.worker.ts (a dedicated same-origin Web Worker that holds all edited-span and ack state: bd-edit:span and bd-edit:exit arrive over the iframe's bd-edit:port MessagePort, ack comes straight from VisualEdit; it is re-armed with a fresh port after a back/forward-cache restore and saves through same-origin POST ycollab/sync or PUT upload/content), and new collab.ts/sharedfile.ts members (onStalled staging replaces the 8s stop() solo fallback, plus saveNow, askingShrink, seenRoomTexts, the pagehide keepalive flush, and the pageshow reset of its exit-send guard); api gains syncCollab and keepalive; Browser waits on FileView's flushRef for Done; Editor binds Mod-s and VisualEdit stages into stageDoc; inline-edit.ts talks to VisualEdit only over a sealed MessageChannel opened by bd-edit:hello, freezes the DOM prototypes it relies on, binds the server's data-src-ranges once and refuses page-script writes to the open element (bd-edit:clobbered); VisualEdit verifies each span against the source (canonicalHTML) before anchoring it.

flowchart LR
    Browser["Browser<br/>✅ Done saves via editFlushRef (saveNow) before leaving; stays on failure or a shrink question"]
    components["components<br/>✅ Editor Mod-s + staging buffer<br/>✅ VisualEdit stageDoc + minimal splice + handle<br/>✅ VisualEdit anchorRanges: canonicalHTML check before anchor / arm<br/>✅ FileView flushRef"]
    frame["✅ lib/frameflush.ts<br/>frameChannel: FIFO message queue, drain()<br/>saveLocked: drain + lock, save, unlock unless saved"]
    inline["inline-edit.ts (iframe bundle, sandbox allow-scripts)<br/>✅ runs before page scripts, captures native MessageChannel / isTrusted<br/>✅ uncurries WeakMap / Map / Set, freezes DOM, Event, Range, Selection, geometry prototypes<br/>✅ binds data-src-ranges once (WeakMap), locks data-bd-src<br/>✅ refuses page-script writes to the open element (inEditorCall)<br/>✅ editor mounted in a closed shadow root (span data-bd-shadow)<br/>✅ pasted marks only from trusted clipboard text/html<br/>✅ answers bd-edit:flush with bd-edit:flushed<br/>✅ lock: true stops edits until bd-edit:unlock<br/>✅ numbers patches (seq), keeps no edited-span map"]
    beacon["✅ lib/editbeacon.ts<br/>ackEditedSpan, unackedExitPatches,<br/>applyRenderPatches, buildExitSaveRequest"]
    worker["✅ lib/editexit.worker.ts<br/>dedicated same-origin Worker: arm / ack / sync / rearm / disarm<br/>holds all edited-span and ack state"]
    hub["same-origin POST ycollab/sync (hub, desktop)<br/>or PUT upload/content with If-Match (plain folder)"]
    collab["lib/collab.ts CollabDoc<br/>❌ <s>stop = solo for good after 8s</s><br/>✅ onStalled (2.5s), encodeState, applySplices, applyRemoteUpdate"]
    merge3["✅ lib/merge3.ts<br/>merge3, merge3PreferRight, merge3ForPath, validMergedText, diffSplices, applySplices, retainsChanges"]
    shared["lib/sharedfile.ts<br/>✅ staging checkpoints + peek recovery<br/>✅ single-flight save, saveNow, askingShrink<br/>✅ pagehide keepalive flush (60,000 bytes), pageshow resets exit guard<br/>✅ seenRoomTexts"]
    api["api/http.ts<br/>✅ syncCollab, putText keepalive"]
    Browser -.->|"✅ Done awaits flushRef"| components
    components -->|openSharedFile| shared
    components -->|"✅ merge3PreferRight diffSplices (VisualEdit)"| merge3
    components -->|"✅ saveLocked(frameChannel drain, saveNow, unlock) (VisualEdit)"| frame
    frame -.->|"✅ bd-edit:flush {lock} / bd-edit:flushed, bd-edit:unlock on a failed save"| inline
    inline -.->|"✅ bd-edit:hello once, with a sealed MessageChannel port"| components
    inline -.->|"✅ bd-edit:clobbered on a page-script write, nothing saved"| components
    components -->|"✅ ack { seq } per applied patch"| worker
    components -->|"✅ spawns + arms (render, allowedRanges, savedText / baseSha / docText via onBaseChange)"| worker
    components -.->|"✅ bd-edit:port (MessageChannel end), fresh one on bfcache pageshow"| inline
    components -->|"✅ rearm on bfcache pageshow"| worker
    inline -->|"✅ bd-edit:span { seq, start, end, html } on each edit, bd-edit:exit on beforeunload / pagehide"| worker
    worker --> beacon
    worker -->|"✅ app's own cookie, keepalive up to 60,000 bytes"| hub
    shared --> collab
    shared -->|"✅ merge3ForPath diffSplices retainsChanges"| merge3
    shared -->|"✅ syncCollab putText keepalive"| api
Loading

Checklist

  • go build ./... && go vet ./... && go test ./... green (including -race across all non-webapp packages and ./internal/webapp -run 'Collab|Concurrent|Stress|Events|Presence|Upload|Store', plus TestCollabEightPeersMeetingNoteExitChaos with 8 concurrent editors across 2 hub instances: 726 edits, 0 conflicts)
  • Sync behavior changes have multi-device tests in internal/syncer (merge_test.go, merge_contentproof_test.go)
  • Frontend changes: npm run build re-committed internal/webapp/static, ./check-dist.sh clean, 35/35 node --test src/lib/sharedfile_restore.test.ts green, and 49/49 Playwright E2E editing/co-editing specs green (edit-url, concurrent-edit, solo-handoff, reconnect, meeting-editor, inline-edit, empty-save, zz-stress-edit)

@isac322 isac322 self-assigned this Nov 11, 2026
@isac322
isac322 requested a review from runbear-bot November 11, 2026 12:18

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • 시각적 편집에서 같은 요소의 충돌이 발생하면 동료의 다른 변경까지 조용히 삭제할 수 있습니다.
  • 새 HTTP 동기화 경로의 쓰기 권한 검사와 조건부 업로드의 JSON 유효성 검사를 확인했습니다. 이전 리뷰 차단 항목은 없습니다.
  • 클린 체크아웃에 패키지 도구와 의존성이 없어 로컬 패키지 테스트는 실행하지 않았습니다.

(live − orig) and ours (html − orig), merged three ways; where they
collide on the same words the patch wins, as it always did. */
const merged = merge3(a.orig, live, msg.html);
const want = merged.ok ? merged.text : msg.html;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 같은 요소의 한 단어에서 충돌하면 merge3가 실패하고 msg.html 전체를 채택하므로, 해당 충돌과 무관한 동료의 다른 편집까지 diffSplices가 삭제하여 공유 문서에 전파합니다. 예를 들어 원문 cat sales, 동료 dog revenue, 내 패치 bird sales는 bird sales가 되어 revenue도 사라집니다. 실패 시 전체 요소로 덮어쓰지 말고 충돌을 보존·표시하거나 충돌한 부분만 별도 해결하면서 다른 변경은 유지해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fc7362f. Added merge3PreferRight in src/lib/merge3.ts and wired both the stageDoc and live paths in VisualEdit.tsx to it so only the colliding token span takes msg.html while non-colliding peer edits in the same element (such as "cat sales" + "dog revenue" + "bird sales" -> "bird revenue") survive intact.

Verified with 36/36 node --test src/lib/sharedfile_restore.test.ts cases (including your cat sales / dog revenue / bird sales case, follow-up keystrokes, and multi-line HTML elements), 18/18 Playwright inline-edit.spec.ts and solo-handoff.spec.ts tests, and ./check-dist.sh.

@isac322
isac322 requested a review from runbear-bot November 11, 2026 12:31

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • 종료 시 충돌 응답을 처리하지 않아 staging/solo 편집 내용이 유실될 수 있습니다.
  • 충돌 복사본 저장의 일시적 실패도 자동 재시도되지 않습니다.
  • 이전 시각적 편집 차단 항목은 토큰 단위 우선 병합으로 수정된 것을 확인했으며, HTTP 동기화 경로의 쓰기 권한 검사도 확인했습니다.
  • 클린 체크아웃에 패키지 도구와 의존성이 없어 로컬 패키지 테스트는 실행하지 않았습니다.

void putText(contentURL(opts.path), text, base, confirmShrinkOnce, true).catch(exitFailed(key));
} else {
opts.soloApply!(e);
void syncCollab(syncURL, roomPayload(text), true).catch(exitFailed(key));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] staging에서 같은 단어를 동료가 먼저 수정한 뒤 이쪽이 유휴 저장 전에 탭을 닫으면 이 요청은 409를 받지만 catch는 전송 키만 초기화합니다. 페이지가 종료되면 버퍼와 함께 내 편집이 사라지고 충돌 복사본도 남지 않습니다. solo의 위 PUT에도 같은 문제가 있습니다. 종료 경로에서도 409 시 keepalive 충돌 복사본으로 보존하거나 종료 전에 내 버퍼의 내구성을 확보해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 34193d0. Because a pagehide keepalive request can outlive the discarded page while its JS cannot run a second request on 409, flushExit now passes park_on_conflict: true on staging POST /ycollab/sync and X-Bdrive-Park-On-Conflict: 1 on solo PUT /upload/content so the hub allocates a collision-free If-None-Match: * conflict copy in that single request when the merge clashes. onExitError also keeps the client-side keepalive conflict-copy PUT as a fallback for older hubs and SPA unmounts.

Verified with 43/43 node --test src/lib/sharedfile_restore.test.ts cases and go test -race ./internal/webapp -run 'ParkOnConflict|TestUpload|TestYCollabSync' (including same-second multi-tab and two-process hub collision tests).

// The same words changed two different ways: genuinely contended.
// Theirs is the file (it got there first); ours goes beside it.
if (landed) adopt(head.text, head.sha);
await preserve(cur, head.sha ?? "");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] solo 저장이 409로 거절되어 실제 충돌을 발견한 뒤 충돌 복사본 PUT이 일시적으로 503/네트워크 오류를 내면, preserve의 실패 결과를 버리고 중단합니다. 이미 유휴 타이머가 소진되어 사용자가 다시 입력하지 않으면 재시도가 없고, Done으로 나가면 유일한 버퍼가 사라질 수 있습니다. 실패 결과를 확인하여 기존 백오프로 같은 복사본을 재시도하고 보존되기 전에는 버퍼를 유지해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 34193d0. Unified conflict parking across sendRoom, rebaseOnHead, and saveLoop MAX_REBASES into parkConflict, which sets stagingConflict = true, keeps the buffer unsaved when preserve fails, arms retryAfterFailure, and retries directly onto the same conflict-copy path in saveLoop (or parks keepalive on flushExit if the editor closes before the retry lands).

Verified with solo 409 clash: a park refused 503 is retried onto the same copy (both with and without close before retry) in src/lib/sharedfile_restore.test.ts (43/43 green) and ./check-dist.sh.

@isac322
isac322 requested a review from runbear-bot November 11, 2026 12:59

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • 일반 저장 및 지연 접속의 충돌 복사본이 다른 탭의 복사본을 덮어써 편집 내용이 유실될 수 있습니다.
  • 이전 시각적 편집의 무관한 변경 보존, 종료 요청의 서버 측 충돌 보관, 일시적 보관 실패 재시도 경로를 확인했습니다. 서버 측 종료 보관은 조건부 생성으로 이름 충돌을 처리하지만 클라이언트 측 보관은 그렇지 않습니다.
  • 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

if (!oursToTheirs || oursToTheirs.from === oursToTheirs.to) {
saved = head.text;
rebase(head.sha);
await putText(contentURL(copy), text); // unconditional: a new path

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 충돌 복사본 이름은 계정과 초 단위 시각으로 만들어지고 lastConflictMs는 탭마다 독립적이므로, 같은 사용자의 두 탭이 같은 파일의 충돌을 같은 초에 보관하면 동일한 경로를 무조건 PUT합니다. 나중 요청이 먼저 보관한 서로 다른 편집을 덮어쓰며 양쪽 모두 저장 성공으로 처리합니다. 기존 복사본이 있는 경우에도 동일합니다. 서버의 parkNewCopy처럼 If-None-Match: *로 원자적으로 생성하고 이름 충돌 시 새 이름으로 재시도하되, 응답 유실 후 동일 요청 재시도도 안전하게 처리해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 88a19c4. preserve(), client exit conflict-copy writes (parkOnExit), and server room conflict-copy writes (parkCopy) now all send If-None-Match: *:

  • When another tab already parked different bytes at that second (409), preserve() mints the next whole-second path via mintConflictPath() and retries (and parkOnExit also sends X-Bdrive-Park-On-Conflict: 1 so the hub steps +1s server-side in one request on pagehide).
  • On a transient 503 or lost response, preserve() keeps the same target path so the backoff retry hits holdsBytes (200 unchanged) idempotently on both hub storage and DirSource without creating a second copy.

Verified with 46/46 node --test src/lib/sharedfile_restore.test.ts cases, go test -race ./internal/webapp -run 'CreateOnly|ParkOnConflict|TestUpload|TestYCollabSync', and ./check-dist.sh.

@isac322
isac322 requested a review from runbear-bot November 11, 2026 13:08

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • staging/solo 종료 시 빈 문서 변경이 전송되지 않아 마지막 삭제가 유실됩니다.
  • 뒤로/앞으로 캐시 복원 후 종료 체크포인트를 기반 상태에 반영하지 않아 이미 보낸 편집이 중복 병합될 수 있습니다.
  • 이전 충돌 복사본 덮어쓰기 차단 항목은 create-only 생성 및 이름 충돌 재시도 경로를 확인했습니다.
  • 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

parkOnExit(copy, text, key);
return;
}
if (!text || text === saved) return;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 빈 문자열도 유효한 편집인데 !text에서 종료하면 staging/solo 문서를 전부 지운 직후 유휴 저장 전에 탭을 닫거나 편집 화면을 떠날 때 삭제가 전송되지 않습니다. 예를 들어 짧은 파일을 모두 지우고 바로 닫으면 기존 내용이 그대로 남습니다. text === saved만으로 변경 여부를 판정하고, 빈 내용도 일반 저장과 동일한 축소 확인 정책을 거쳐 종료 체크포인트로 보내 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6a088a6. flushExit now checks text === saved && !roomNeedsFlush without skipping !text, so clearing a buffer to "" goes through the exit checkpoint and shrink-confirmation policy (askShrink on 422 when the page remains live), while blank conflict copies remain suppressed.

Verified with 55/55 node --test src/lib/sharedfile_restore.test.ts cases and ./check-dist.sh.

opts.onConflictCopy?.(path);
});
};
const landed = (out: { parked?: string }) => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] pagehide 체크포인트 성공 시 저장된 텍스트/sha와 전송 이력을 갱신하지 않아 bfcache에서 복원된 staging 편집기가 이미 반영된 내용을 다시 옛 base에서 병합합니다. 예를 들어 log\n에서 x\n을 추가하고 pagehide 요청이 성공한 뒤 복원하여 x\n을 하나 더 추가하면 서버는 같은 위치에 x와 x,x를 독립 삽입으로 합쳐 세 줄을 저장합니다. 종료 요청도 일반 staging 체크포인트처럼 성공 시 응답을 적용하고, 응답이 불확실하거나 복원과 경합할 때는 전송 이력을 기록해 peek/prior_sent로 정산해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6a088a6. Staging flushExit now tracks the exit request in ambiguousRoomCheckpoint and exitSaving (awaited by both save() and join() if the page returns from bfcache while the request is still in flight), applies out.update, and updates saved/base on completion across staging and solo so post-pageshow edits build on the landed state or pass prior_sent/peek without duplicating lines.

Verified with 55/55 node --test src/lib/sharedfile_restore.test.ts cases (covering landed, 502, unsettled, and late-join() bfcache restoration) and ./check-dist.sh.

@isac322
isac322 requested a review from runbear-bot November 11, 2026 13:20

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • 클라이언트 재병합이 서버의 JSON 유효성 검사를 우회하여 유효한 두 편집을 잘못된 JSON으로 저장할 수 있습니다.
  • 이전 지적의 빈 버퍼 전송, bfcache 체크포인트 정산, 충돌 복사본 조건부 생성 경로를 확인했습니다.
  • 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

const room = typeof theirs.text === "string" ? theirs.text : null;
if (room !== null) {
const res = merge3(saved, room, current());
if (res.ok && applyText(res.text)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 서버가 병합 결과의 JSON 유효성 실패로 409를 반환해도 여기서는 텍스트 병합만 성공하면 결과를 적용하고 새 room 기준으로 다시 전송합니다. 예를 들어 [와 ] 사이에 각각 1과 2를 삽입한 두 유효한 JSON 배열은 쉼표 없는 [\n1\n2\n]로 합쳐지고, 재전송은 최신 base에 대한 직접 쓰기라 서버의 병합 유효성 검사를 통과하여 원본을 손상시킵니다. .json/.jsonl 결과를 적용하기 전에 서버와 동일하게 검증하고 실패 시 충돌 복사본으로 보존해 주세요. solo 재기반 및 늦은 join 경로에도 같은 검사가 필요합니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8942b1b. Added validMergedText and merge3ForPath in src/lib/merge3.ts (matching Go's .json and .jsonl validation, while leaving one-sided edits unchecked so in-progress JSON typing is unaffected) and routed all 8 client merge/rebase sites in src/lib/sharedfile.ts through mergeForPath. Invalid combined JSON/JSONL merges on staging 409, solo rebaseOnHead, late join(), and external merge() now park a conflict copy or report "blocked" instead of rebasing and overwriting the file.

Verified with 59/59 node --test src/lib/sharedfile_restore.test.ts cases (covering staging 409, solo 409, late join(), and .jsonl validation) and ./check-dist.sh.

@isac322
isac322 requested a review from runbear-bot November 11, 2026 13:29

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • Done 저장이 지연되는 동안 축소 확인창이 열려도 타임아웃이 편집기를 닫아 확인과 편집 내용을 잃을 수 있습니다.
  • 이전 지적의 클라이언트 JSON/JSONL 병합 검증, 빈 버퍼 전송 및 충돌 복사본 create-only 경로를 확인했습니다.
  • 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

try {
okToLeave = await Promise.race([
editFlushRef.current?.() ?? Promise.resolve(true),
new Promise<boolean>((r) => setTimeout(() => r(true), 1_500)),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 저장 요청이 1.5초 이상 걸리는 동안 축소 확인창이 열려도 이 타임아웃은 무조건 true를 반환하여 Done이 편집기를 닫습니다. 예를 들어 라이브 문서 내용을 대폭 지우고 Done을 누른 뒤 요청이 지연되면 700ms의 watchShrink가 확인창을 열지만, 1.5초에 편집기가 파괴되면서 질문이 철회되고 삭제도 저장되지 않습니다. 타임아웃 후에도 현재 askingShrink()를 별도로 확인해 질문이 열려 있으면 이탈을 막고, 지연 응답에서 질문이 열리는 경합도 처리해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a94090b:

  1. saveNow() in src/lib/sharedfile.ts now checks sharpShrink(byteLength(saved), byteLength(current())) synchronously before sending any request whenever this tab has unsent edits, opening the shrink dialog immediately without waiting on the network.
  2. FileView.tsx owns the bounded Done wait (1.5s, or 5s when data.text === "" && !!data.sha so a hub-detected truncated-read shrink has room to answer) and checks !f.askingShrink() after the wait settles rather than resolving true from a timer in Browser.tsx.

Verified with 64/64 node --test src/lib/sharedfile_restore.test.ts cases (including hung-network sharp shrinks across live, offline, staging, and solo modes plus slow server 422 responses) and ./check-dist.sh.

@isac322
isac322 requested a review from runbear-bot November 11, 2026 13:39

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • Done 대기 시간이 끝난 뒤 서버만 감지할 수 있는 축소 거절이 도착하면 확인 없이 편집기가 닫히고 미저장 편집이 유실될 수 있습니다. 이전 리뷰의 지연 응답 경합이 완전히 해결되지 않았습니다.
  • 빈 버퍼 전송, bfcache 체크포인트 정산, JSON/JSONL 병합 검증 및 충돌 복사본 create-only 경로를 확인했습니다.
  • 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

// Promise constructor, not withResolvers: the app targets ES2022.
let timer: ReturnType<typeof setTimeout> | undefined;
const waited = new Promise<void>((r) => {
timer = setTimeout(r, onlyHubSeesShrink ? 5_000 : 1_500);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 서버만 감지하는 축소는 5초 뒤에도 여전히 422를 반환할 수 있습니다. 예를 들어 불완전하게 읽힌 빈 seed에서 편집 후 Done을 누르고 응답이 5초 넘게 지연되면 타이머가 먼저 이탈을 허용합니다. 이후 422는 이미 파괴된 편집기에 도착해 확인창을 열지 못하고 변경도 저장되지 않습니다. 고정 대기 시간을 늘리는 대신 이 경우 결과가 확정될 때까지 이탈을 막거나, 늦은 422에서도 편집 버퍼와 확인 절차가 살아남도록 처리해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 87c6406. Replaced the fixed 5,000 ms timer with mayServerRefuseShrink() on SharedFile: whenever only the server can detect a shrink (an empty saved === "" paired with a non-empty base SHA, or a solo/noRoomHttp conditional PUT where the server's file may have grown), FileView.tsx awaits saveNow() until it settles before allowing Done to leave, while keeping the 1,500 ms cap for ordinary saves where local sharpShrink already ran synchronously.

Verified with 65/65 node --test src/lib/sharedfile_restore.test.ts cases (including a 10,000 ms delayed server 422 test and mayServerRefuseShrink coverage across all modes) and ./check-dist.sh.

@isac322
isac322 requested a review from runbear-bot November 11, 2026 13:46

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • 이전 Done/축소 확인 경합은 빈 seed 이외의 라이브 룸에서도 재현되어 미해결입니다.
  • 빈 버퍼 종료 전송, bfcache 정산, JSON 병합 검증 및 충돌 복사본의 create-only 경로를 확인했습니다.
  • 클린 체크아웃에서 로컬 패키지 테스트는 실행하지 않았습니다.

mayServerRefuseShrink: () => {
if (asking || gone || confirmShrinkOnce || !opts.onShrinkRefused) return false;
if (!base || base === EMPTY_SHA256) return false;
if (hubHoldsIt) return saved === "" && (localDirtyInRoom || pending > 0);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 라이브 룸에서 saved가 비어 있지 않더라도 서버만 축소를 감지할 수 있습니다. 예를 들어 다른 편집자가 큰 내용을 추가해 허브가 스냅샷을 저장했지만 이 탭의 파일 변경 알림은 아직 도착하지 않은 상태에서, 사용자가 그 내용을 삭제하고 기존 짧은 텍스트에 단어를 추가하면 saved 대비로는 축소가 아니지만 서버 파일 대비로는 급격한 축소입니다. mustSettle이 false이므로 Done은 1.5초 뒤 편집기를 닫고, 늦게 도착한 422는 파괴된 편집기에서 확인할 수 없어 저장되지 않습니다. 룸의 저장된 최신 크기를 확실히 알 수 없는 경우에도 결과가 확정될 때까지 이탈을 막거나 늦은 422를 처리할 버퍼와 확인 절차를 유지해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9fe7bba. Removed mayServerRefuseShrink and the fixed 1,500 ms timer completely so FileView.tsx awaits f.saveNow() until it settles in every mode (including a live room where a peer's snapshot grew the server file before SSE notified this tab) and checks !f.askingShrink(), with leavingFlushRef guarding duplicate clicks on the active editor's flush closure.

Verified with 65/65 node --test src/lib/sharedfile_restore.test.ts cases (including a 10,000 ms delayed 422 shrink refusal on a non-empty live room) and ./check-dist.sh.

@isac322
isac322 requested a review from runbear-bot November 11, 2026 13:56

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • Done 저장 중 추가 편집은 저장 결과를 기다리지 않고 이탈해 늦은 축소 거절과 편집 유실이 다시 발생할 수 있습니다.
  • 저장 실패도 성공처럼 이탈해 재시도가 취소되고 미저장 버퍼가 파괴될 수 있습니다.
  • 기존 고정 타임아웃 제거와 빈 버퍼 종료 전송, JSON 병합 검증 및 충돌 복사본 create-only 경로를 확인했습니다.
  • 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

if (out.update) collab.applyRemoteUpdate(out.update);
adopt(out.text, out.sha);
// Typing that landed while this was out is not in it.
roomHandedOver(sentRoomSeq);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Done이 이 요청을 기다리는 동안에도 편집기는 활성 상태입니다. 요청 이후 사용자가 추가 편집하면 roomHandedOver(sentRoomSeq)가 dirty 상태를 유지하지만 이 Promise는 그대로 완료되어 Done이 편집기를 닫습니다. 특히 추가 편집이 축소라면 teardown의 별도 요청에서 늦게 422가 도착해도 이미 파괴된 편집기에서 확인할 수 없습니다. 저장 중 편집을 막거나 새 sequence까지 반복 체크포인트하고 각 결과/축소 확인이 정산된 뒤에만 Done이 이탈하게 해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a14f2a4. saveNow() now loops while owesSave() remains true (running askIfShrunk() before each pass), so edits or shrinks typed while an earlier pass is on the wire are checkpointed and shrink-checked before saveNow() resolves.

Verified with 72/72 node --test src/lib/sharedfile_restore.test.ts cases (including concurrent typing and concurrent shrinks during in-flight saveNow() across live and solo modes) and ./check-dist.sh.

} catch {
// The editor's own teardown still sends what it holds.
}
if (f.askingShrink()) return false;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] saveNow()는 네트워크 오류나 403/503을 내부에서 처리하고 정상 완료할 수 있으므로 축소 확인만 검사하면 저장되지 않은 상태에서도 Done이 이탈합니다. 예를 들어 staging 저장이 503이면 재시도가 예약되지만 unmount의 destroy()가 이를 취소하고 종료 요청 한 번만 시도하므로 장애가 지속되면 유일한 편집 버퍼가 사라집니다. 저장 성공/실패를 명시적으로 반환하고 미저장 또는 보존 실패 시 편집기를 유지하여 재시도할 수 있게 해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a14f2a4. saveNow() now returns Promise<boolean> (false whenever a shrink confirmation opens or a pass fails to advance due to 503/403/network error or an unparked conflict), and FileView.tsx keeps the editor and its retry timers open whenever !saved || f.askingShrink().

Verified with 72/72 node --test src/lib/sharedfile_restore.test.ts cases (covering 503 failures and subsequent recovery across live, offline, staging, solo, and conflict-park paths) and ./check-dist.sh.

@isac322
isac322 requested a review from runbear-bot November 11, 2026 14:17
@isac322
isac322 requested a review from runbear-bot November 11, 2026 18:51

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • 비신뢰 iframe의 DOM 쓰기 차단이 다른 JavaScript realm의 네이티브 메서드 및 반사 속성 setter로 우회될 수 있어 이전 보안 차단 문제가 완전히 해소되지 않았습니다.
  • 프레임 채널 분리, 범위 내용 대조 및 bfcache worker 재무장 경로를 확인했습니다.
  • 클린 체크아웃에 패키지 의존성과 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

};

// The open element and everything in it.
setters(Element.prototype, ["innerHTML", "outerHTML"], (s) => hostWrite(s, []));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 이 래퍼는 현재 realm의 프로토타입만 보호합니다. 비신뢰 HTML이 about:blank 자식 iframe의 Element.prototype.innerHTML 원본 setter를 얻어 열린 편집 요소에 call하면 이 검사를 거치지 않고 DOM을 바꿀 수 있습니다. HTMLAnchorElement.href 같은 반사 속성 setter도 별도로 가로채지 않습니다. 특히 실제 붙여넣기 중에는 allowRichPaste가 켜져 텍스트 예산과 일치하는 변경에 임의의 링크 마크가 섞일 수 있으므로 사용자 입력에 편승한 내용 변경을 배제하지 못합니다. DOM 공유 realm의 프로토타입 패치에 의존하지 않는 격리된 편집 경계에서 입력을 수집하고, 다른 차단 시도를 섞지 않은 교차 realm setter/링크 변조와 실제 붙여넣기 회귀 테스트를 추가해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b2098d7:

  • mount(el) (src/inline-edit.ts) now isolates ProseMirror's active editing DOM inside a closed Shadow Root (rawAttachShadow.call(shadowHost, { mode: "closed" }), captured at $t = 0$ before any page script runs), cloning inert page stylesheets and built-in ancestor selector context (safeMirrorTag, refusing hyphenated custom elements) into the closed shadow tree and writing the serialized inner HTML back onto el's light DOM on unmount().
  • Because shadowRoot is null across all realms and events retarget outside the closed boundary, pre-saved light-DOM references (HTMLAnchorElement.prototype.href setter, even during real paste when allowRichPaste is active!), event-target queries, and cross-realm about:blank Element.prototype.innerHTML setters cannot reach ProseMirror's live nodes; detaching el or shadowHost triggers clobberFromScript() (bd-edit:clobbered) without saving.
  • Added all 3 isolated, unmixed Chromium Playwright E2E regression tests in e2e/inline-edit.spec.ts (24/24 E2E tests pass):
    1. Pure reflected HTMLAnchorElement.prototype.href setter during real typing,
    2. Pure cross-realm about:blank Element.prototype.innerHTML setter during real typing, and
    3. Real user paste (ControlOrMeta+v) while hostile paste/beforeinput/input listeners attempt link href hijacking and clipboard markup injection.

@isac322
isac322 requested a review from runbear-bot November 11, 2026 19:18

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • 닫힌 shadow root의 내부 노드가 페이지가 교체한 DOM 메서드를 통해 노출되어 이전 보안 차단 문제가 여전히 남습니다.
  • iframe 채널 분리와 bfcache 재무장 경로를 확인했습니다. 클린 체크아웃에서 로컬 패키지 테스트는 실행하지 않았습니다.

noticeable way a click-to-edit surface can feel broken. */
function caretAt(v: EditorView, x: number, y: number) {
const at = v.posAtCoords({ left: x, top: y });
const rect = v.dom.getBoundingClientRect();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 비신뢰 페이지가 편집 시작 전에 Element.prototype.getBoundingClientRect를 교체하면 실제 클릭으로 caretAt이 호출될 때 래퍼의 this로 닫힌 shadow root 안의 v.dom을 획득합니다. this.getRootNode() 및 하위 노드에 접근할 수 있으므로 다른 realm의 네이티브 setter나 href setter로 편집 중인 DOM을 변조할 수 있고, 특히 실제 붙여넣기 중에는 변경이 사용자 입력에 편승해 저장될 수 있습니다. 기존 cross-realm 차단 문제가 해소되지 않았습니다. 비신뢰 코드와 편집기를 별도 실행 경계로 격리하고, 프로토타입 메서드 교체로 내부 노드를 탈취한 뒤 실제 붙여넣기 중 링크를 변조하는 회귀 테스트를 추가해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 10a5961:

  • caretAt now calls native Element.prototype.getBoundingClientRect captured at $t = 0$, and installGuards() freezes all DOM/WebIDL, Event, Range, Selection, and geometry prototypes (proto instanceof EventTarget || proto instanceof Event || extraDOMProtos.has(proto)) before any page script executes so page scripts cannot replace Element.prototype.getBoundingClientRect, getClientRects, HTMLElement.prototype.focus, or ShadowRoot.prototype.* to steal v.dom or this.getRootNode().
  • parseMarkup / parseInner / serializeInner now parse HTML inside a fresh inert <template> rather than walking live page-owned DOM nodes.
  • Replaced the blanket allowRichPaste boolean with allowedPasteMarks: Set<string> extracted strictly from the trusted ClipboardEvent/InputEvent text/html payload, so unchanged spans always enforce PMMark.sameSet even during a paste and pasted text may only carry marks present in the clipboard's text/html (or cursor/adjacent marks).
  • Added the prototype-method replacement + shadow-node theft + real paste link-tampering E2E regression test in e2e/inline-edit.spec.ts (stolen === 0, 25/25 Playwright E2E tests pass).

@isac322
isac322 requested a review from runbear-bot November 11, 2026 19:29

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • 비신뢰 페이지가 변경 가능한 JavaScript 내장 프로토타입을 통해 종료 패치를 위조할 수 있어 이전 보안 차단 문제가 남아 있습니다.
  • 닫힌 shadow root 보호, 범위 검증 및 bfcache 재무장 경로를 확인했습니다.
  • 클린 체크아웃에 패키지 의존성과 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

frame, decides whether and how it is saved. */
function exitUnacked() {
if (!exitPort) return;
const patches = unackedExitPatches(editedSpans.values());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Map.prototype은 동결되지 않아 비신뢰 페이지가 values를 교체하면 여기서 호출될 때 비공개 editedSpans 맵을 this로 얻고 각 항목의 html과 acked를 바꿀 수 있습니다. 사용자가 정상 편집 후 탭을 닫으면 위조된 범위 내용이 봉인된 포트로 worker에 전달되고, 유효한 범위와 script 없는 HTML이므로 세션 권한으로 저장됩니다. shadow root 및 신뢰 이벤트 검사를 우회하는 경로입니다. 비신뢰 코드와 편집 상태를 별도 실행 경계로 격리하고, 내장 프로토타입 교체로 종료 패치를 변조하는 회귀 테스트를 추가해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0a6851e:

  • Moved editedSpans, ackEditedSpan, and unackedExitPatches completely out of src/inline-edit.ts into src/lib/editexit.worker.ts's isolated WorkerGlobalScope realm: inline-edit.ts streams { type: "bd-edit:span", seq, start, end, html } on each edit and { type: "bd-edit:exit" } (with no payload) on unload, while VisualEdit.tsx sends { type: "ack", seq } directly to editexit.worker.ts (retaining early acks in ackedSeqs so ack and bd-edit:span commute across channels).
  • Uncurried all internal WeakMap/Map/Set/MessagePort operations in inline-edit.ts at $t = 0$ via Function.prototype.bind.bind(Function.prototype.call), so page scripts replacing Map.prototype.values/set, Array.prototype.sort/map, JSON.stringify, or Function.prototype.call cannot observe or tamper with exit patches.
  • Added the Map/Array/JSON prototype-replacement exit-patch regression test in e2e/inline-edit.spec.ts (26/26 Playwright E2E tests pass).

@isac322
isac322 requested a review from runbear-bot November 11, 2026 19:46

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • 비신뢰 페이지가 범위 검증 이후 편집 시작 전에 요소 내용을 바꾸면 사용자 권한으로 위조된 내용이 저장되는 보안 차단 문제가 남아 있습니다.
  • 이전 Map 기반 종료 패치 변조는 worker 분리로 해소되었으나, 최초 범위 검증과 편집 시작 사이의 내용 무결성은 보장되지 않습니다.
  • 클린 체크아웃에 패키지 의존성과 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

Unanchored Findings (outside changed diff lines)

  • internal/webapp/frontend/src/inline-edit.ts:842: [P1] initDOM에서 기록한 initialHtml은 부모가 한 번만 검증하지만, 비신뢰 페이지 스크립트는 그 이후 host가 아직 없을 때 해당 요소의 innerHTML을 자유롭게 바꿀 수 있습니다. 사용자가 그 요소를 클릭하면 여기서 변조된 현재 DOM을 편집기 초기 문서로 읽고, 정상적으로 한 글자만 입력해도 flush()가 변조 내용 전체를 유효한 범위의 패치로 전송하여 사용자 세션 권한으로 저장합니다. 편집 시작 시 신뢰된 원본과 현재 내용을 다시 대조하고 불일치하면 편집을 거부하거나, 검증된 원본을 별도 신뢰 경계에서 편집기에 공급해 주세요. 초기화 후 클릭 전 DOM 변조 회귀 테스트도 필요합니다.

@isac322

isac322 commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

Re: unanchored finding on src/inline-edit.ts:842 in review 5864539766:

Fixed in 3af174b:

  • boundRanges now stores frozen null-prototype BoundRange records ({ start, end, expectedHtml }), initialized at initDOM() and updated by unmount() only when writing back a valid user edit.
  • Both editable(el, announceClobber) and mount(el) call verifiedBound(el, ...), verifying elInnerHTMLGet.call(el) === b.expectedHtml before mounting and parsing b.expectedHtml through parseMarkup rather than live DOM nodes; if a page script rewrote el after initDOM() while host === null, verifiedBound marks el non-editable, records it in tamperedElements so clicking announces bd-edit:clobbered, and refuses to mount.
  • Added the post-initialization pre-click DOM tampering regression test in e2e/inline-edit.spec.ts (27/27 Playwright E2E tests pass).

@isac322
isac322 requested a review from runbear-bot November 11, 2026 19:55

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • 비신뢰 페이지가 변경 가능한 배열 프로토타입을 통해 편집기의 내부 마크를 탈취·변조하여 사용자 권한으로 저장할 수 있습니다.
  • 이전 지적의 클릭 전 DOM 변조 검증과 종료 worker 분리 경로를 확인했으나, 공유 JavaScript realm의 무결성 문제는 남아 있습니다.
  • 클린 체크아웃에서 로컬 패키지 테스트는 실행하지 않았습니다.

doc.descendants((node) => {
if (!node.isText || !node.text) return;
const t = node.text.replace(/\u00a0/g, " ");
for (let i = 0; i < t.length; i++) out.push({ ch: t[i], marks: node.marks });

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 비신뢰 페이지가 편집 전에 Array.prototype.push를 교체하면 실제 입력 중 이 호출의 인자로 전달되는 node.marks에 접근할 수 있습니다. 예를 들어 기존 링크의 rawInline 마크에 있는 marks[0].attrs.attrs.href를 바꾸면 이전/다음 ProseMirror 문서가 공유하는 마크 자체가 변조되어 비교와 입력 예산 검사를 통과하고, 정상 타이핑에 편승해 위조된 링크가 저장됩니다. 닫힌 shadow root와 worker 분리로도 보호되지 않습니다. 비신뢰 코드와 편집 상태를 별도 실행 경계로 분리하고, 최소한 변경 가능한 내장 메서드에 내부 마크 참조를 넘기지 않도록 하며 이 프로토타입 교체 후 실제 타이핑하는 회귀 테스트를 추가해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4d98490:

  • RawInline.parseHTML().getAttrs now stores attrs on a Object.freeze(Object.create(null)) record, so mark.attrs.attrs (href) cannot be mutated in place even if a reference were obtained.
  • charsWithMarks and the mark-diff loop in dispatchTransaction no longer invoke .push, .slice, .map, .join, .includes, or .every via mutable prototype lookups (using indexed assignment onto frozen null-prototype CharUnit records and uncurried strReplace/strIncludes).
  • installGuards() locks all existing own methods/accessors on JS built-in intrinsics (Array.prototype, Map.prototype, String.prototype, RegExp.prototype, Function.prototype, JSON, Reflect, etc.) as writable: false, configurable: false (leaving prototypes extensible for new polyfill methods while sealing Object.prototype with SES-style safe-override accessors).
  • Added the Array.prototype.push/map/slice + Object.prototype mark-tampering regression test during real typing in e2e/inline-edit.spec.ts (28/28 Playwright E2E tests pass).

@isac322
isac322 requested a review from runbear-bot November 11, 2026 20:05

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • bfcache 진입 시 종료 저장이 실패하면 미전달 편집을 이미 저장된 것으로 표시해, 복귀 후 다음 종료에서도 편집이 유실될 수 있습니다.
  • 기존 클릭 전 DOM 무결성 검사, 내장 프로토타입 잠금 및 bfcache 채널 재무장 경로와 협업 HTTP 쓰기 권한 계약을 확인했습니다.
  • 클린 체크아웃에 의존성과 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

childPort?.close();
childPort = null;
const patches = unackedExitPatches(editedSpans.values());
for (const s of editedSpans.values()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] bfcache 진입 시 부모가 아직 받지 못한 편집을 여기서 네트워크 요청 전에 승인 처리합니다. 오프라인이나 503 등으로 아래 fetch가 실패해도 rearm은 이 상태를 유지하므로, 복귀 후 다른 영역을 편집하고 다시 닫으면 첫 편집이 ackedHtml 조상에만 포함되어 실제 문서에서 삭제된 것으로 병합되거나 재전송 대상에서 빠집니다. 요청의 성공 및 실제 반영을 확인한 뒤에만 해당 스냅샷을 승인하고, 실패·모호한 결과에서는 미승인 상태를 유지해 복귀 후 재시도/조회를 하도록 수정해 주세요. 첫 종료 저장 실패 → pageshow → 두 번째 편집 및 종료 회귀 테스트가 필요합니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 58f546a:

  • sendUnacked (src/lib/editexit.worker.ts) no longer marks editedSpans acknowledged before fetch completes: confirmSeqs(sentSeqs) runs only after a confirmed 200 OK (out.ok === true).
  • On 5xx (including 503) or network/ambiguous failures, spans remain unacknowledged (acked: false), recordAmbiguous retains priorSentTexts (prior_sent on ycollab/sync), and reconcileAfterRearm() on pageshow probes { peek: true } to advance ackedHtml/docText when the live room already holds the attempt while keeping s.acked = false and scheduling scheduleRearmRetry() until a durable sync succeeds (with buildExitSaveRequest still sending when reverting back to savedText over an outstanding ambiguous room state).
  • Added the failed-first-exit (503) -> pageshow -> second undelivered edit -> tab-close E2E regression test in e2e/inline-edit.spec.ts (29/29 Playwright E2E tests pass).

@isac322
isac322 requested a review from runbear-bot November 11, 2026 20:22

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: not-ready

  • bfcache 복귀 후 종료 저장 재시도와 새 편집 승인 응답이 역순으로 도착하면 편집 조상이 뒤로 이동하여 후속 종료 저장에서 내용이 중복될 수 있습니다.
  • 실패한 종료 요청을 성공 전에 승인하지 않는 수정과 재무장·재시도 경로를 확인했습니다.
  • 클린 체크아웃에 의존성과 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

if (!exited && !disarmed && state === curState) reconcileAfterRearm();
return;
}
confirmSeqs(sentSeqs);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 복귀 후 이전 종료 편집의 재시도가 진행 중일 때 같은 요소를 다시 편집하면 앱의 새 ack가 먼저 ackedHtml을 최신 내용으로 전진시킬 수 있습니다. 이후 늦게 도착한 이 요청의 성공 응답이 이전 sentSeqs를 다시 승인하면서 ackEditedSpan이 ackedHtml을 이전 내용으로 되돌립니다. 다음 미전달 편집의 종료 저장은 이미 앱 문서에 반영된 새 편집을 조상에 없는 삽입으로 다시 병합해 중복할 수 있습니다. 범위별로 마지막 승인 seq를 기록하고 오래된 승인이 조상을 덮어쓰지 않게 하며, 재시도 응답보다 새 ack가 먼저 도착한 뒤 같은 요소를 다시 편집·종료하는 회귀 테스트를 추가해 주세요.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d85c0c7:

  • EditedSpan (src/lib/editbeacon.ts) now tracks monotonic ackedSeq, and ackEditedSpan (as well as peek and bd-edit:span updates in editexit.worker.ts) advances ackedHtml only when s.ackedSeq === undefined || seq > s.ackedSeq, so a late exit-save response confirming an older seq never rolls ackedHtml backward behind a newer app ack (and workerSaved only updates while state.savedText === fromText).
  • Added both unit assertions in sharedfile_restore.test.ts and the out-of-order late exit-save response + same-element edit + close E2E regression test in e2e/inline-edit.spec.ts (30/30 Playwright E2E tests pass).

@isac322
isac322 requested a review from runbear-bot November 11, 2026 20:32

@runbear-bot runbear-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bobb's bot(Totoro) Review

Conclusion: ready-with-notes

  • 이전 차단 사항인 종료 저장 실패 후 미승인 유지와 역순 승인 시 범위별 ackedSeq 단조 증가 처리를 확인했습니다.
  • 협업 HTTP 동기화의 경로 쓰기 권한 검사와 syncer의 승자 콘텐츠 기반 병합·중복 생략 계약을 확인했습니다.
  • 클린 체크아웃에 패키지 의존성과 실행 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.

@isac322
isac322 merged commit a63eed0 into main Nov 11, 2026
5 checks passed
@isac322
isac322 deleted the fix/collab-journal-fenced-diff3 branch November 11, 2026 21:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants